// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-11-6

#ifndef __NET_SOCKDATA_H_COMMON_SERVLIB__
#define __NET_SOCKDATA_H_COMMON_SERVLIB__

#pragma once

#include "net_config.h"
#include <common/base/refdata.h>

namespace JoyServer
{

class CJoySocket;

// socket object can be used in several threads.
// use CJoySockData to manage the socket handle and 
// other important datas.
class CJoySockData : public CJoyRefData
{
public:
    volatile CJoySocket*    m_owner;
    CJoyCriticalSection     m_ownerLock;
    SOCKET  m_handle;
    DWORD   m_closeTime;
    DWORD   m_closeTimeout;

    CJoyAtomCount   m_sendCount;
    bool m_bStream;
    bool m_bRecv;

    CJoySockData();
    virtual ~CJoySockData();
};

// before close a socket object, we sometimes want to 
// send the last data block such as an error message.
// so we use a queue to hold the socket data, release
// socket datas until the last data block was sent.
class CJoyReleaseSockData
{
protected:
    CJoyCriticalSection     m_lock;
    CList<CJoySockData*>    m_datas;
    HANDLE  m_event;
    HANDLE  m_thread;
    volatile bool   m_stop;

public:
    CJoyReleaseSockData();
    ~CJoyReleaseSockData();

    static DWORD WINAPI sReleaseProc(void*);
    DWORD WINAPI ReleaseProc();

    CJoySockData* PeekData();
    void PostData(CJoySockData* pData);
    void ReleaseDatas();

    void Init();
    void Free();
};

} // namespace JoyServer

#endif  // __NET_SOCKDATA_H_COMMON_SERVLIB__